<template>
  <div class="chat-container">
    <!-- 头部导航 -->
    <van-nav-bar
      title="AI学伴"
      left-arrow
      @click-left="$router.back()"
      class="chat-header"
    >
      <template #right>
        <van-icon name="more-o" size="18" />
      </template>
    </van-nav-bar>

    <!-- 消息列表 -->
    <div class="message-list" ref="messageListRef">
      <div
        class="message-wrapper"
        v-for="(message, index) in messages"
        :key="index"
      >
        <!-- 时间戳 -->
        <!-- <div class="time-stamp" v-if="shouldShowTime(message, index)">
          {{ formatTime(message.timestamp) }}
        </div> -->

        <!-- 消息气泡 -->
        <div
          class="message-item"
          :class="{
            'message-right': message.type === 'user',
            'message-left': message.type === 'ai',
          }"
        >
          <!-- AI头像 -->
          <div class="avatar" v-if="message.type === 'ai'">
            <van-image
              width="40"
              height="40"
              round
              fit="cover"
              :src="aiAvatar"
              alt="AI助手"
            />
          </div>

          <!-- 消息内容 -->
          <div class="message-bubble" :class="message.type">
            <div class="message-content">
              <div
                v-if="message.type === 'ai' && message.typing"
                class="typing-indicator"
              >
                <span></span>
                <span></span>
                <span></span>
              </div>
              <div v-else v-html="formatMessage(message.content)"></div>
              <div class="message-btns" v-if="message.type === 'ai'">
                <span class="shuziren"
                  ><img src="@/assets/images/voice-icon.png" alt="数字人讲解" />
                  数字人讲解</span
                >
                <span class="copy" @click="copyMessage(message.content)"
                  ><img src="@/assets/images/copy-icon.png" alt="复制" />
                  复制</span
                >
              </div>
            </div>
          </div>

          <!-- 用户头像 -->
          <div class="avatar" v-if="message.type === 'user'">
            <van-image
              width="40"
              height="40"
              round
              fit="cover"
              :src="userAvatar"
              alt="用户"
            />
          </div>
        </div>
      </div>

      <!-- 占位符，用于滚动到底部 -->
      <div ref="scrollAnchor" style="height: 1px"></div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <!-- 输入框 -->
      <div class="input-container">
        <div class="input-wrapper">
          <van-field
            v-model="inputValue"
            placeholder="输入消息..."
            type="textarea"
            rows="1"
            autosize
            @keyup.enter="handleEnter"
            class="message-input"
          />

          <van-button
            :disabled="!inputValue.trim() || sending"
            @click="sendMessage"
            type="primary"
            size="small"
            round
            class="send-btn"
            :loading="sending"
          >
            <van-icon name="send" v-if="!sending" />发送
          </van-button>
        </div>
      </div>
    </div>

    <!-- 图片预览 -->
    <van-image-preview
      v-model:show="showImagePreview"
      :images="previewImages"
      :start-position="previewIndex"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed, watch } from "vue";
import { showToast, showImagePreview as vanShowImagePreview } from "vant";

// 响应式数据
const messageListRef = ref(null);
const scrollAnchor = ref(null);
const inputValue = ref("");
const sending = ref(false);
const showImagePreview = ref(false);
const previewImages = ref([]);
const previewIndex = ref(0);

// 用户和AI头像
const userAvatar = ref("https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg");
const aiAvatar = ref("https://fastly.jsdelivr.net/npm/@vant/assets/logo.png");

// 消息列表
const messages = ref([
  {
    id: 1,
    type: "ai",
    content: "你好！我是智能助手，有什么可以帮助你的吗？",
    timestamp: Date.now() - 60000,
  },
  {
    id: 2,
    type: "user",
    content: "你好，请介绍一下你的功能",
    timestamp: Date.now() - 30000,
  },
  {
    id: 3,
    type: "ai",
    content:
      "我可以帮助你回答问题、进行对话、提供建议等。你可以问我任何问题，我会尽力为你提供有用的信息！",
    timestamp: Date.now() - 10000,
  },
]);

// 方法
const shouldShowTime = (message, index) => {
  if (index === 0) return true;
  const prevMessage = messages.value[index - 1];
  return message.timestamp - prevMessage.timestamp > 5 * 60 * 1000; // 5分钟间隔显示时间
};

const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const messageDate = new Date(
    date.getFullYear(),
    date.getMonth(),
    date.getDate()
  );

  if (messageDate.getTime() === today.getTime()) {
    return date.toLocaleTimeString("zh-CN", {
      hour: "2-digit",
      minute: "2-digit",
    });
  } else {
    return (
      date.toLocaleDateString("zh-CN", { month: "short", day: "numeric" }) +
      " " +
      date.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" })
    );
  }
};

const formatMessage = (content) => {
  // 简单的文本格式化，可以扩展支持markdown等
  return content.replace(/\n/g, "<br>");
};

const scrollToBottom = () => {
  nextTick(() => {
    if (scrollAnchor.value) {
      scrollAnchor.value.scrollIntoView({ behavior: "smooth" });
    }
  });
};

const sendMessage = async () => {
  if (!inputValue.value.trim() || sending.value) return;

  const userMessage = {
    id: Date.now(),
    type: "user",
    content: inputValue.value.trim(),
    timestamp: Date.now(),
  };

  messages.value.push(userMessage);
  const messageContent = inputValue.value.trim();
  inputValue.value = "";
  scrollToBottom();

  // 模拟AI回复
  sending.value = true;

  // 添加打字指示器
  const typingMessage = {
    id: Date.now() + 1,
    type: "ai",
    content: "",
    timestamp: Date.now(),
    typing: true,
  };
  messages.value.push(typingMessage);
  scrollToBottom();

  try {
    // 这里可以调用实际的AI API
    await new Promise((resolve) => setTimeout(resolve, 1500));

    // 移除打字指示器
    const typingIndex = messages.value.findIndex((msg) => msg.typing);
    if (typingIndex > -1) {
      messages.value.splice(typingIndex, 1);
    }

    // 添加AI回复
    const aiReply = getAIReply(messageContent);
    const aiMessage = {
      id: Date.now() + 2,
      type: "ai",
      content: aiReply,
      timestamp: Date.now(),
    };

    messages.value.push(aiMessage);
    scrollToBottom();
  } catch (error) {
    showToast("发送失败，请重试");
    console.error("发送消息失败:", error);
  } finally {
    sending.value = false;
  }
};

const getAIReply = (userMessage) => {
  // 简单的模拟回复逻辑
  const replies = {
    你好: "你好！很高兴与你对话！",
    功能: "我具备对话聊天、问题解答、内容创作等多种能力，随时为你提供帮助！",
    天气: "很抱歉，我暂时无法获取实时天气信息。建议你查看天气APP获取准确信息。",
    美食: "推荐一些经典美食：\n🍜 兰州拉面\n🥟 小笼包\n🍲 麻辣火锅\n🥘 宫保鸡丁\n你想了解哪种美食的做法？",
    笑话: "为什么程序员总是分不清Halloween和Christmas？\n因为 Oct 31 == Dec 25！😄",
  };

  for (const [key, reply] of Object.entries(replies)) {
    if (userMessage.includes(key)) {
      return reply;
    }
  }

  return `我理解你说的是"${userMessage}"。作为AI助手，我会尽力帮助你。有什么具体问题我可以为你解答吗？`;
};

const selectQuickReply = (reply) => {
  inputValue.value = reply;
  sendMessage();
};

const handleEnter = (event) => {
  if (!event.shiftKey) {
    event.preventDefault();
    sendMessage();
  }
};

const copyMessage = (content) => {
  navigator.clipboard.writeText(content);
  showToast("复制成功");
};

// 生命周期
onMounted(() => {
  scrollToBottom();
});

// 监听消息变化，自动滚动到底部
watch(
  messages,
  () => {
    scrollToBottom();
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
.chat-container {
  height: 100vh;
  background: #f5f6fb;
  display: flex;
  flex-direction: column;
}

.chat-header {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  --van-nav-bar-title-text-color: #1f2937;
  --van-nav-bar-icon-color: #6b7280;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px 16px 0;

  &::-webkit-scrollbar {
    display: none;
  }
}

.message-wrapper {
  margin-bottom: 20px;
}

.time-stamp {
  text-align: center;
  color: #9ca3af;
  font-size: 24px;
  margin-bottom: 16px;
  position: relative;

  &::before {
    content: "";
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    height: 1px;
    background: #e5e7eb;
    z-index: 1;
  }

  &::after {
    content: attr(data-time);
    background: #f7f8fc;
    padding: 0 16px;
    position: relative;
    z-index: 2;
  }
}

.message-item {
  display: flex;
  margin-bottom: 16px;
  animation: fadeInUp 0.3s ease;

  &.message-right {
    justify-content: flex-end;

    .message-bubble {
      margin-right: 12px;
    }
  }

  &.message-left {
    justify-content: flex-start;

    .message-bubble {
      margin-left: 12px;
    }
  }
}

.avatar {
  flex-shrink: 0;

  :deep(.van-image) {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border: 2px solid #fff;
  }
}

.message-bubble {
  max-width: 70%;
  position: relative;

  &.user {
    .message-content {
      background: #dce9ff;
      color: #1f2937;
      border-radius: 10px;
    }
  }

  &.ai {
    .message-content {
      background: #fff;
      color: #1f2937;
      border-radius: 10px;

      .message-btns {
        margin-top: 10px;
        display: flex;
        color: #457aff;
        font-size: 12px;
        cursor: pointer;
        .shuziren {
          margin-right: 20px;
        }
        .copy {
        }
      }
    }
  }
}

.message-content {
  padding: 12px 16px;
  font-size: 16px;
  line-height: 1.5;
  word-break: break-word;
  position: relative;

  :deep(br) {
    line-height: 1.8;
  }
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;

  span {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #d1d5db;
    animation: typing 1.4s infinite ease-in-out;

    &:nth-child(2) {
      animation-delay: 0.2s;
    }

    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

.input-area {
  background: #fff;
  border-top: 1px solid #f3f4f6;
  padding: 12px;
}

.quick-replies {
  margin-bottom: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.quick-reply-tag {
  --van-tag-primary-color: #667eea;
  cursor: pointer;
  transition: all 0.2s ease;

  &:active {
    transform: scale(0.95);
  }
}

.input-container {
  position: relative;
}

.input-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  background: #f8fafc;
  border-radius: 24px;
  padding: 8px;
  border: 1px solid #e2e8f0;
  transition: all 0.2s ease;

  &:focus-within {
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  }
}

.message-input {
  flex: 1;

  :deep(.van-field__control) {
    background: transparent;
    border: none;
    resize: none;
    font-size: 16px;
    line-height: 1.5;
    max-height: 120px;

    &::placeholder {
      color: #9ca3af;
    }
  }

  :deep(.van-field__word-limit) {
    font-size: 14px;
    color: #9ca3af;
  }
}

.send-btn {
  background: #457aff;
  flex-shrink: 0;
  min-width: 64px;
  transition: all 0.2s ease;

  &:not(:disabled):active {
    transform: scale(0.95);
  }

  &:disabled {
    opacity: 0.5;
  }
}

// 动画
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes typing {
  0%,
  60%,
  100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  30% {
    transform: scale(1);
    opacity: 1;
  }
}

// // 响应式适配
// @media (max-width: 375px) {
//   .message-bubble {
//     max-width: 75%;
//   }

//   .message-content {
//     font-size: 16px;
//     padding: 10px 14px;
//   }

//   .input-area {
//     padding: 12px;
//   }
// }

// // 深色模式适配（可选）
// @media (prefers-color-scheme: dark) {
//   .chat-container {
//     background: linear-gradient(180deg, #1f2937 0%, #111827 100%);
//   }

//   .chat-header {
//     background: #1f2937;
//     --van-nav-bar-title-text-color: #f9fafb;
//     --van-nav-bar-icon-color: #d1d5db;
//   }

//   .message-bubble.ai .message-content {
//     background: #374151;
//     color: #f9fafb;
//     border-color: #4b5563;
//   }

//   .input-wrapper {
//     background: #374151;
//     border-color: #4b5563;
//   }

//   .input-area {
//     background: #1f2937;
//     border-top-color: #4b5563;
//   }
// }
</style>
